package cn.hongsw.taskschedule.db;

import com.baomidou.dynamic.datasource.provider.AbstractJdbcDataSourceProvider;
import com.baomidou.dynamic.datasource.provider.DynamicDataSourceProvider;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DataSourceProperty;
import com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Map;

/**
 * @author :hongsw
 * @date :2021-05-19 9:25
 */
@Configuration
public class DataSourceConfig {
    @Resource
    private DynamicDataSourceProperties dynamicDataSourceProperties;

    @Bean
    public DynamicDataSourceProvider dynamicDataSourceProvider() {
        String[] params = new String[4];
        dynamicDataSourceProperties.getDatasource().forEach((k, v) -> {
            params[0] = v.getDriverClassName();
            params[1] = v.getUrl();
            params[2] = v.getUsername();
            params[3] = v.getPassword();
        });
        return new AbstractJdbcDataSourceProvider(params[0], params[1], params[2], params[3]) {
            @Override
            protected Map<String, DataSourceProperty> executeStmt(Statement statement) throws SQLException {
                Map<String, DataSourceProperty> map = new HashMap<>();
                DataSourceProperty masterProperty = new DataSourceProperty();
                masterProperty.setDriverClassName(params[0]);
                masterProperty.setUrl(params[1]);
                masterProperty.setUsername(params[2]);
                masterProperty.setPassword(params[3]);
                map.put("master", masterProperty);
                ResultSet rs = statement.executeQuery("select * from data_source_info");
                while (rs.next()) {
                    String name = rs.getString("id");
                    String username = rs.getString("username");
                    String password = rs.getString("password");
                    String url = rs.getString("url");
                    String driver = rs.getString("driver_class_name");
                    DataSourceProperty property = new DataSourceProperty();
                    property.setUsername(username);
                    property.setPassword(password);
                    property.setUrl(url);
                    property.setDriverClassName(driver);
                    map.put(name, property);
                }
                return map;
            }
        };
    }
}
